#include "WarningSys.h"
#include "FLASH.h"
#include "stdio.h"
#include "string.h"
#include "Time.h"
#include "Delay.h"
#include "BUZZER.h"
#include "LED.h"

extern int year;
extern int month;
extern int day;
extern int hour;
extern int minute;
extern int sec;

#define WARNING_DELAY_MS 100
#define MAX_DUTY_CYCLE 100
#define DUTY_INCREMENT 10


static void Warning(void) {
    static int buzzerInitialized = 0;
    if (!buzzerInitialized) {
        Buzzer_Init();
        buzzerInitialized = 1;
    }
  
	Tim3_Init();
    // 缓慢增大占空比
    for (int i = 0; i <= MAX_DUTY_CYCLE; i += DUTY_INCREMENT) {
        TIM_SetCompare3(TIM3, i);
        Delay_ms(WARNING_DELAY_MS);
    }
    // 缓慢减小占空比
    for (int i = MAX_DUTY_CYCLE; i > 0; i -= DUTY_INCREMENT) {
        TIM_SetCompare3(TIM3, i);
        Delay_ms(WARNING_DELAY_MS);
    }
	Led_TurnOn();
	Led_TurnOff();
	Led_TurnOn();
	Led_TurnOff();
	Led_TurnOn();
	Led_TurnOff();
	TIM_Cmd(TIM3, DISABLE);
}


static void LDR_Warning(void) {
      Warning();
	Flash_Write(0x00,(const u8*)"LDR", 3);
	u8 data[3] = {0};
    Flash_Read(0x00, data, 3);
    printf("%s Log:Excessive light intensity:%04d%02d%02d%02d%02d%02d\n", data,year, month, day, hour, minute, sec);
}

static void DHT11_TempWarning(void) {
    Warning();
	Flash_Write(0x32,(const u8*)"DHT11", 5);
	u8 data[5] = {0};
    Flash_Read(0x32, data, 5);
    printf("%s Log:Excessive temperature:%04d%02d%02d%02d%02d%02d\n", data,year, month, day, hour, minute, sec);
	
}

static void DHT11_HumWarning(void) {
	Warning();
	Flash_Write(0x64,(const u8*)"DHT11", 5);
	u8 data[5] = {0};
    Flash_Read(0x64, data, 5);
    printf("%s Log:Excessive humidity:%04d%02d%02d%02d%02d%02d\n", data,year, month, day, hour, minute, sec);
	
}

void warningSys(u8 LDR, u8 temp, u8 hum) {
    if (LDR > 60) {
        LDR_Warning();
    } 
  
    if (temp > 40) {
        DHT11_TempWarning();
    } 

    if (hum > 80) {
        DHT11_HumWarning();
    } 
}

